package com.hanoi.wiki.manager.impl;

import java.util.ArrayList;
import java.util.List;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
import org.springframework.transaction.annotation.Transactional;

import com.hanoi.wiki.dao.CategorySubTypeDAO;
import com.hanoi.wiki.dao.CategoryTypeDAO;
import com.hanoi.wiki.exception.DataAccessException;
import com.hanoi.wiki.manager.CategorySubTypeManager;
import com.hanoi.wiki.model.CategorySubType;
import com.hanoi.wiki.model.CategoryType;
import com.hanoi.wiki.model.json.CategorySubTypeJson;

@Component
@Transactional
public class CategorySubTypeManagerImpl extends BaseManagerImpl implements CategorySubTypeManager{

	@Autowired
	private CategorySubTypeDAO categorySubTypeDAO;
	
	@Autowired
	private CategoryTypeDAO categoryTypeDAO;
	
	public int save(CategorySubTypeJson json) {
		try {
			CategorySubType subType = new CategorySubType(json);
			
			List<CategoryType> categoryTypes = new ArrayList<CategoryType>();
			CategoryType categoryType;
			for(Integer i : json.getCategoryType()) {
				categoryType = categoryTypeDAO.get(i);
				if(categoryType != null) {
					categoryTypes.add(categoryType);
				}
			}
			
			subType.setCategoryTypes(categoryTypes);
			
			return categorySubTypeDAO.saveCategorySubType(subType);
		} catch (DataAccessException e) {			
			log.error("", e);
		}
		return 0;
	}

	
	public void update(CategorySubTypeJson json) {
		try {
			CategorySubType subType = new CategorySubType(json);
			
			List<CategoryType> categoryTypes = new ArrayList<CategoryType>();
			CategoryType categoryType;
			for(Integer i : json.getCategoryType()) {
				categoryType = categoryTypeDAO.get(i);
				if(categoryType != null) {
					categoryTypes.add(categoryType);
				}
			}
			
			subType.setCategoryTypes(categoryTypes);
			subType.setId(json.getId());
			
			categorySubTypeDAO.update(subType);
		} catch (DataAccessException e) {			
			log.error("", e);
		}
	}

	
	public CategorySubTypeJson get(Integer id) {
		try {
			return new CategorySubTypeJson(categorySubTypeDAO.get(id));
		} catch (DataAccessException e) {			
			log.error("", e);
		}
		return null;
	}

	
	public List<CategorySubTypeJson> getList() {
		List<CategorySubTypeJson> cstjList = new ArrayList<CategorySubTypeJson>();
		List<CategorySubType> cstList = categorySubTypeDAO.getList();
		try {
			for(CategorySubType subType : cstList) {
				cstjList.add(new CategorySubTypeJson(subType));
			}
		} catch (DataAccessException e) {			
			log.error("", e);
		}
		return cstjList;
	}

	
	public void remove(Integer id) {
		try {
			if(categorySubTypeDAO.get(id) != null) {
				categorySubTypeDAO.remove(id);
			}
		} catch (DataAccessException e) {			
			log.error("", e);
		}
	}

}
